package com.suxii.Thread;

import android.graphics.Color;
import android.util.Log;

import com.suxii.handler.MyHandler;
import com.suxii.netty_demo.activity.Suxii;
import com.suxii.pojo.PingMsg;
import com.suxii.procotol.ChatCodec;
import com.suxii.service.MyNettyService;

import java.net.InetSocketAddress;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;

public class NettyThread extends Thread{
    public static Channel channel=null;


    @Override
    public void run() {
        b();
    }

    private void b() {
        NioEventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.channel(NioSocketChannel.class);
            b.group(group);
            b.handler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new ChatCodec()); //添加编解码器
                    // 每25s发送一个心跳包
                    ch.pipeline().addLast(new IdleStateHandler(0,25,0));
                    ch.pipeline().addLast(new MyHandler()); //接收消息
                    ch.pipeline().addLast(new ChannelDuplexHandler(){
                        @Override
                        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                            IdleStateEvent event=(IdleStateEvent) evt;
                            if (event.state() == IdleState.WRITER_IDLE) {
                                //Log.e("aa","3s未发送消息，发送心跳包");
                                ctx.channel().writeAndFlush(new PingMsg());
                            }
                        }

                    });

                }
            });
            ChannelFuture future = b.connect(new InetSocketAddress(MyNettyService.host, MyNettyService.port));
            future.addListener(f -> {
                Log.e("aa",f.isSuccess()+":"+f.cause());
                setText(f.isSuccess());
            });
            channel = future.channel();
            //channel.writeAndFlush("123 123");

            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
            Log.e("aa","优雅的关闭流");
            setText(false);
            // 停止服务
            /*Intent intent=new Intent(context, MyNettyService.class);
            context.stopService(intent);*/
            if (channel!=null) {
                channel.close();
                channel=null;
            }
        }
    }
    public void setText(boolean isConnect){
        if (Suxii.circle!=null) {
            Suxii.circle.post(()->{
                if (isConnect) {
                    Suxii.circle.setCardBackgroundColor(Color.GREEN);
                }else {
                    Suxii.circle.setCardBackgroundColor(Color.RED);
                }
            });
        }
    }
}
